<?php

class Account extends MX_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->lang->load('error', $this->public_model->getLanguage());
    }

    function index()
    {
        $this->load->helper('url');
        redirect('/account/profile_setting', 'refresh');
        //        $data = array();
        //        $data['menu'] = modules::run('account/menu');
        //        $acontent = $this->load->view('profile_view', $data, true);
        //        Template::display($acontent);
    }
    function menu()
    {
        $data = array();
        $menu = $this->uri->segment(2);

        $menuExchange = '';
        if ($menu == 'pointExchange')
            $menuExchange = 'Point';

        elseif ($menu == 'coinExchange')
            $menuExchange = 'Coin';

        elseif ($menu == 'moneyExchange')
            $menuExchange = 'Money';

        $data['menuExchange'] = $menuExchange;
        $this->load->view('menu_vertical_view', $data);
    }

    function profile_setting()
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            $this->session->set_userdata('refered_from', 'account/profile_setting');
            redirect('/login');
            return;
        }
        $ci=& get_instance();
        $ci->load->model('game/game_model');
        
        $user_id = $this->session->userdata('id');
        $this->load->model('account_model');

        $data = array();
        $data['menu'] = modules::run('account/menu');
        $data['user_detail'] = $this->account_model->getUser($user_id);
        $data['player'] = $ci->game_model->getPlayer($user_id);
        $acontent = $this->load->view('profile_view', $data, true);
        Template::display($acontent);
    }
    function payment_setting()
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            $this->session->set_userdata('refered_from', 'account/payment_setting');
            redirect('/login');
            return;
        }
        $user_id = $this->session->userdata('id');
        $this->load->model('account_model');
        $this->load->library('form_validation');
        $CI = &get_instance();
        $CI->load->model('pay/pay_model');


        $data = array();
        //layout
        $data['menu'] = modules::run('account/menu');
        

        $action = $this->input->post('submit');
        
        if ($action != null && $action == 'Update') //update payment account
        {
            $data['form_payment_account'] = 'show';
            $this->form_validation->set_rules('billAddress1', 'Address 1',
                'trim|required|max_length[255]');
            $this->form_validation->set_rules('billAddress2', 'Address 2', 'max_length[255]');
            $this->form_validation->set_rules('billCity', 'City', 'trim|required');
            $this->form_validation->set_rules('billState', 'State', '');
            $this->form_validation->set_rules('billStateText', 'State', '');
            $this->form_validation->set_rules('billCountry', 'Country', '');
            $this->form_validation->set_rules('billZip', 'Zip Code',
                'max_length[9]|numeric|min_length[5]|');
            $this->form_validation->set_rules('billPhone1', 'Phone 1',
                'exact_length[3]|numeric');
            $this->form_validation->set_rules('billPhone2', 'Phone 2',
                'callback_validatephone');
            $this->form_validation->set_rules('billPhone3', 'Phone 3',
                'max_length[5]|numeric');
            if ($this->form_validation->run($this) == false)
            {
                $data['result'] = false;
                $data['message'] = validation_errors();
            } else
            {
                //update payment account _ address
                $address_id = $this->input->post('address_id');
                $date_update = array();
                $date_update['street_address_1'] = $this->input->post('billAddress1');
                $date_update['street_address_2'] = $this->input->post('billAddress2');
                $date_update['city'] = $this->input->post('billCity');
                if ($this->input->post('billHasState') == 'yes')
                    $date_update['state'] = $this->input->post('billState');
                else
                    $date_update['state'] = $this->input->post('billStateText');
                $date_update['zip_code'] = $this->input->post('billZip');
                $date_update['country'] = $this->input->post('billCountry');
                $date_update['area_code'] = $this->input->post('billPhone1');
                $date_update['phone_number'] = $this->input->post('billPhone2');
                $date_update['phone_extension'] = $this->input->post('billPhone3');

                $this->db->where('id', $address_id);
                $this->db->update('addresses', $date_update);

                $data['result'] = true;
                $data['message'] = 'Updated success.';

            }
            
        } elseif ($action != null && $action == 'Create') //create new payment
        {
            $data['form_new_payment_account'] = 'show';
            
            //set rules : credit card info
            $this->form_validation->set_rules('createPaymentName', 'Card holder Name', 'trim|required|max_length[100]');
			$this->form_validation->set_rules('createPaymentNumber', 'Card Number', 'trim|required|max_length[16]|min_length[16]');
			$this->form_validation->set_rules('createPaymentCVV2Code', 'CVV Code', 'trim|required|max_length[4]');
            
            //set rules : address
            $this->form_validation->set_rules('createPaymentBillAddress1', 'Address 1','trim|required|max_length[255]');
            $this->form_validation->set_rules('createPaymentBillAddress2', 'Address 2', 'max_length[255]');
            $this->form_validation->set_rules('createPaymentBillCountry', 'Country', '');
            $this->form_validation->set_rules('createPaymentBillCity', 'City', 'trim|required');
            
            $this->form_validation->set_rules('createPaymentBillState', 'State', '');
            $this->form_validation->set_rules('createPaymentBillStateText', 'State', '');
            
            $this->form_validation->set_rules('createPaymentBillZip', 'Zip Code','max_length[9]|numeric|min_length[5]|');
            $this->form_validation->set_rules('createPaymentBillPhone1', 'Phone 1','exact_length[3]|numeric');
            $this->form_validation->set_rules('createPaymentBillPhone2', 'Phone 2','callback_validatephone');
            $this->form_validation->set_rules('createPaymentBillPhone3', 'Phone 3','max_length[5]|numeric');
            
            if ($this->form_validation->run($this) == false)
            {
                $data['result'] = false;
                $data['message'] = validation_errors();
            } else
            {
                $this->load->library('payment');
                //payment account
                $data_cc['cardType'] = $this->input->post('createPaymentCardType');
                $data_cc['cardName'] = $this->input->post('createPaymentName');
                $data_cc['cardNumber'] = $this->input->post('createPaymentNumber');
                $data_cc['cardCVV'] = $this->input->post('createPaymentCVV2Code');
                $data_cc['cardExpireMonth'] = $this->input->post('createPaymentExpireMonth');
                $data_cc['cardExpireYear'] = $this->input->post('createPaymentExpireYear');
                //address
                $data_cc['paymentAddress1'] = $this->input->post('createPaymentBillAddress1');
                $data_cc['paymentAddress2'] = $this->input->post('createPaymentBillAddress2');
                $data_cc['paymentCountry'] = $this->input->post('createPaymentBillCountry');
                $data_cc['paymentHasState'] = $this->input->post('createPaymentHasState');
                $data_cc['paymentBillCity'] = $this->input->post('createPaymentBillCity');
                $data_cc['paymentBillState'] = $this->input->post('createPaymentBillState');
                $data_cc['paymentBillStateText'] = $this->input->post('createPaymentBillStateText');

                $data_cc['paymentBillZip'] = $this->input->post('createPaymentBillZip');
                $data_cc['paymentBillPhone1'] = $this->input->post('createPaymentBillPhone1');
                $data_cc['paymentBillPhone2'] = $this->input->post('createPaymentBillPhone2');
                $data_cc['paymentBillPhone3'] = $this->input->post('createPaymentBillPhone3');

                //phan tich name
                $arr_temp = array();
                $arr_temp = explode(' ', $data_cc['cardName']);
                $first_name = '';
                $last_name = '';
                if (count($arr_temp) > 0)
                {
                    for ($i = 0; $i < count($arr_temp) - 1; $i++)
                    {
                        $first_name = $first_name . $arr_temp[$i] . ' ';
                    }
                    if ($first_name != '')
                    {
                        $first_name = substr($first_name, 0, -1);
                    } else
                    {
                        $first_name = $arr_temp[0];
                    }
                    if (count($arr_temp) > 1)
                    {
                        $last_name = $arr_temp[count($arr_temp) - 1];
                    } else
                    {
                        $last_name = '';
                    }
                } else
                {
                    $first_name = $this->input->post('paymentName');
                    $last_name = '';
                }
                //$this->payment->makePayment()
                //saving payment account
                $creditCardInfo = array(
                    'cardNum' => $this->payment->encrypt($data_cc['cardNumber']),
                    'creditCardLast4Digits' => substr($data_cc['cardNumber'], strlen($data_cc['cardNumber']) -
                        4, 4),
                    'expYear' => $data_cc['cardExpireYear'],
                    'expMonth' => $data_cc['cardExpireMonth'],
                    'cardCodePresent' => 'ValuePresent',
                    'cardCode' => $data_cc['cardCVV'],
                    'cardholderFirstName' => $first_name,
                    'cardholderLastName' => $last_name,
                    'cardHolderCompanyName' => null,
                    'cardHolderFullName' => $first_name . " " . $last_name,
                    'track1' => null,
                    'track2' => null,
                    'streetAddressLine1' => $data_cc['paymentAddress1'],
                    'zip' => $data_cc['paymentBillZip'],
                    'ext' => (isset($zipcode[1]) ? $zipcode[1] : ""),
                    'cardType' => $data_cc['cardType'],
                    'entryMode' => 'Manual',
                    'signature' => null,
                    'cardPresent' => 'NO',
                    );
                $response = $this->payment->submitCreatePaymentAccount($creditCardInfo);
                if ($response != null && $response->success == true)
                {
                    $data_insert_address = array();
                    $data_insert_address['first_name'] = $first_name;
                    $data_insert_address['middle_name'] = '';
                    $data_insert_address['last_name'] = $last_name;
                    $data_insert_address['prefix'] = '';
                    $data_insert_address['suffix'] = '';
                    $data_insert_address['street_address_1'] = $data_cc['paymentAddress1'];
                    $data_insert_address['street_address_2'] = $data_cc['paymentAddress2'];
                    $data_insert_address['city'] = $data_cc['paymentBillCity'];
                    if ($data_cc['paymentHasState'] == 'yes')
                    {
                        $states = $this->pay_model->getStates($data_cc['paymentCountry']);
                        for ($i = 0; $i < count($states); $i++)
                        {
                            if ($states[$i]->id == $data_cc['paymentBillState'])
                            {
                                $data_insert_address['state'] = $states[$i]->name;
                                break;
                            }
                        }
                    } else
                        $data_insert_address['state'] = $data_cc['paymentBillStateText'];
                    $data_insert_address['zip_code'] = $data_cc['paymentBillZip'];
                    $data_insert_address['country'] = $data_cc['paymentCountry'];
                    $data_insert_address['area_code'] = $data_cc['paymentBillPhone1'];
                    $data_insert_address['phone_number'] = $data_cc['paymentBillPhone2'];
                    $data_insert_address['phone_extension'] = $data_cc['paymentBillPhone3'];
                    $data_insert_address['email_address'] = $this->session->userdata('email');
                    $data_insert_address['company_name'] = '';
                    $this->db->insert('addresses', $data_insert_address);
                    $address_id = $this->db->insert_id();

                    //insert paymentaccount
                    $data_insert_pc = array();
                    $data_insert_pc['user_id'] = $user_id;
                    $data_insert_pc['address_id'] = $address_id;
                    $data_insert_pc['payment_account_id'] = $response->clientRequestNumber;
                    $data_insert_pc['default'] = 0;
                    $data_insert_pc['active'] = 1;
                    $this->db->insert('paymentaccounts', $data_insert_pc);
                    
                    $data['result'] = true;
                    $data['message'] = 'Created success.';
                }
                else
                {
                    $data['result'] = false;
                    if (isset($response->commonResponse))
                    {
                        if (isset($response->commonResponse->displayMessages))
                            $data['message'] = $response->commonResponse->displayMessages;
                        elseif (isset($response->commonResponse->errorDescription))
                            $data['message'] = $response->commonResponse->errorDescription;
                    }
                }
            }
        }

        $data['countries'] = $CI->pay_model->getCountries();
        
        //getting payment accounts information
        $data['paymentAccounts'] = $CI->pay_model->getPaymentAccounts($user_id);
        if (count($data['paymentAccounts']) > 0)
        {
            $data['paymenttransactions'] = array();
            for ($i = 0; $i < count($data['paymentAccounts']); $i++)
                array_push($data['paymenttransactions'], $CI->pay_model->getPaymenttransactions
                    ($data['paymentAccounts'][$i]->payment_account_id));
            $data['address'] = $CI->pay_model->getAddress($data['paymentAccounts'][0]->
                address_id);
            $data['states'] = $CI->pay_model->getStates($data['address']->country);
        }
        else
        {
            if (count($data['countries'])>0)
                $data['states'] = $CI->pay_model->getStates($data['countries'][0]->id);
            else
                $data['states'] = '';
        }
        
        $acontent = $this->load->view('payment_view', $data, true);
        Template::display($acontent);
    }

    function ajax_updateProfileSetting()
    {
        $data = array();
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $auto_withdraw = $this->input->post('auto_withdraw');
        $this->load->model('account_model');
        $user_id = $this->session->userdata('id');

        if ($first_name == null || $last_name == null)
        {
            $data['result'] = false;
            $data['message'] = "Need first name and last name.";
        } else
        {
            $this->account_model->updateName($user_id, $first_name, $last_name);
            $this->account_model->updatePlayer(array('auto_withdraw'=>$auto_withdraw), $user_id);
            $data['result'] = true;
            $data['message'] = "Update profile success.";
        }
        echo json_encode($data);
    }

    function ajax_updatePassword()
    {
        $this->load->model('membership_model');
        $this->load->library('form_validation');
        $data = array();

        $password = $this->input->post('password');
        $newpassword = $this->input->post('newpassword');
        $confirmnewpassword = $this->input->post('confirmnewpassword');

        $user_id = $this->session->userdata('id');

        if (!empty($password))
        {
            $user = $this->membership_model->get_member_info(null, null, $password, $user_id);
            if (!$user)
            {
                $data['aaaresult'] = $password;
                $data['result'] = false;
                $data['message'] = "Current password is not correct.";
            } else
            {
                if ($password != '' && $confirmnewpassword != '' && $newpassword == $confirmnewpassword &&
                    strlen($newpassword) >= 6)
                {
                    $this->membership_model->update_password();
                    $data['result'] = true;
                    $data['message'] = "Your password has been changed successfully.";
                } else
                {
                    $data['result'] = false;
                    $data['message'] = "New password error.";
                }
            }
        } else
        {
            $data['result'] = false;
            $data['message'] = "Need your current password .";
        }
        echo json_encode($data);
    }
}
